package org.mzy.basic.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.mzy.basic.config.BussinessException;
import org.mzy.basic.constant.BaseConstants;
import org.mzy.basic.service.IRegisterService;
import org.mzy.basic.util.MD5Utils;
import org.mzy.basic.util.StrUtils;
import org.mzy.user.domain.Logininfo;
import org.mzy.user.domain.User;
import org.mzy.user.dto.EmailRegisterDto;
import org.mzy.user.dto.PhoneRegisterDto;
import org.mzy.user.mapper.LogininfoMapper;
import org.mzy.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /*手机注册*/
    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        // 验证参数
        this.verifyPhoneParam(dto);
        // 插 先插logininfo 再插user
        User user = this.dtoConvertUser(dto);
        Logininfo logininfo = this.userConvertLogininfo(user);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /*邮箱注册*/
    @Override
    public void emailRegister(EmailRegisterDto dto) {
        // 验证参数
        this.verifyEmailParam(dto);
        // 插 先插logininfo 再插user
        User user2 = this.dtoConvertUser2(dto);
        Logininfo logininfo = this.userConvertLogininfo(user2);
        // 添加
        logininfoMapper.add(logininfo);
        user2.setLogininfoId(logininfo.getId());
        userMapper.add(user2);
    }

    // 将user对象转换为logininfo的方法
    private Logininfo userConvertLogininfo(User user) {
        // new一个Logininfo对象，将user中相同字段复制到logininfo中，并返回
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        return logininfo;
    }

    // 将手机登录的dto实体类转换为user对象
    private User dtoConvertUser(PhoneRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + dto.getPassword();
        String encryPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();

    }

    // 将邮箱登录的dto实体类转换为user对象
    private User dtoConvertUser2(EmailRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + dto.getPassword();
        String encryPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getEmail())
                .email(dto.getEmail())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();

    }

    // 验证手机参数
    private void verifyPhoneParam(PhoneRegisterDto dto) {
        // 判断非空
        if (StringUtils.isBlank(dto.getPassword()) || StringUtils.isBlank(dto.getPasswordRepeat()) || StringUtils.isBlank(dto.getPhone()) || StringUtils.isBlank(dto.getSmsCode())) {
            throw new BussinessException("参数不能为空！");
        }
        // 两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 验证码是否正确 / 两次手机号是否一致
        String redisSmsCode = (String) redisTemplate.opsForValue().get(
                String.format(BaseConstants.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        if (StringUtils.isBlank(redisSmsCode)) {
            throw new BussinessException("验证码错误！");
        }
        String[] smsCode = redisSmsCode.split(":");
        if (!smsCode[0].equals(dto.getSmsCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 是否注册过
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user) {
            throw new BussinessException("该手机号已被注册！");
        }
    }

    // 验证邮箱参数
    private void verifyEmailParam(EmailRegisterDto dto) {
        // 判断非空
        if (StringUtils.isBlank(dto.getPassword()) || StringUtils.isBlank(dto.getPasswordRepeat()) || StringUtils.isBlank(dto.getEmail()) || StringUtils.isBlank(dto.getEmailCode())) {
            throw new BussinessException("参数不能为空！");
        }
        // 两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 验证码是否正确 / 两次手机号是否一致
        String redisSmsCode = (String) redisTemplate.opsForValue().get(
                String.format(BaseConstants.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getEmail()));
        if (StringUtils.isBlank(redisSmsCode)) {
            throw new BussinessException("验证码错误！");
        }
        // 分割字符串，获取验证码
        String[] smsCode = redisSmsCode.split(":");
        if (!smsCode[0].equals(dto.getEmailCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 是否注册过
        User user = userMapper.findByEamil(dto.getEmail());
        if (null != user) {
            throw new BussinessException("该邮箱已被注册！");
        }
    }
}